package com.whl.sm.service.impl.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whl.sm.mapper.system.RoleMapper;
import com.whl.sm.model.system.Role;
import com.whl.sm.service.system.OrgUserService;
import com.whl.sm.service.system.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuhaolun
 * @since 2021-09-10
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private OrgUserService orgUserService;

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public int update(Role role) {
        role.setOperator(orgUserService.getCurrentUserId());
        if (StringUtils.isNotBlank(role.getId())){
            role.setType(null);
            roleMapper.updateById(role);
        }
        else {
            List<Role> typeList = roleMapper.selectList(new QueryWrapper<Role>()
                    .eq("type",role.getType())
                    .orderByDesc("create_time")
            );
            int insertOrderNum = 1;
            if (typeList.size()>0){

                insertOrderNum = typeList.get(0).getOrderNum()+1;
            }
            role.setOrderNum(insertOrderNum);
            roleMapper.insert(role);
        }
        return 0;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public int deleteByList(List<String> idList) {
        int result = roleMapper.deleteBatchIds(idList);
        return result;
    }

    @Override
    public List<Role> getRoleTypeList() {
        List<Role> roleTypeList = new ArrayList<>();
        Role role1 = new Role(); role1.setId("1"); role1.setRoleName("系统管理员");
        Role role2 = new Role(); role2.setId("2"); role2.setRoleName("小区管理员");
        Role role3 = new Role(); role3.setId("3"); role3.setRoleName("住户");
        roleTypeList.add(role1); roleTypeList.add(role2); roleTypeList.add(role3);
        for (Role role : roleTypeList){
            role.setChildren(
                    getBaseMapper().selectList(
                            new QueryWrapper<Role>().eq("type",role.getId())
                    )
            );
        }
        return roleTypeList;
    }
}
